<!-- @ts-nocheck -->
<template>
  <view class="product-container">
    <!-- 状态栏占位 -->
    <view :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 页面标题 -->
    <view class="page-header">
      <view class="title-section">
        <text class="page-title">商品管理</text>
        <text class="date">{{ currentDate }}</text>
      </view>
      <view class="refresh-btn" @click="refreshData">
        <uni-icons type="refresh" size="18" color="#FF8C42"></uni-icons>
      </view>
    </view>

    <!-- 商品统计概览 -->
    <view class="stats-overview">
      <view class="stats-grid">
        <!-- 商品总数 -->
        <view class="stat-card">
          <view class="stat-icon product-icon">
            <uni-icons type="gift" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">商品总数</text>
            <text class="stat-value">{{ productStats.totalProducts }}</text>
          </view>
        </view>
        
        <!-- 在售商品 -->
        <view class="stat-card">
          <view class="stat-icon sales-icon">
            <uni-icons type="cart" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">在售商品</text>
            <text class="stat-value">{{ productStats.activeProducts }}</text>
          </view>
        </view>
        
        <!-- 库存预警 -->
        <view class="stat-card">
          <view class="stat-icon warning-icon">
            <uni-icons type="notification" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">库存预警</text>
            <text class="stat-value">{{ productStats.lowStockCount }}</text>
          </view>
        </view>
        
        <!-- 已下架 -->
        <view class="stat-card">
          <view class="stat-icon inactive-icon">
            <uni-icons type="eye-slash" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">已下架</text>
            <text class="stat-value">{{ productStats.inactiveProducts }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 操作按钮区域 -->
    <view class="action-bar">
      <view class="search-box">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input 
          type="text" 
          v-model="searchKeyword" 
          placeholder="搜索商品名称" 
          confirm-type="search"
          @confirm="searchProducts"
          @input="onSearchInput"
        />
        <view v-if="searchKeyword" class="clear-search" @click="clearSearch">
          <uni-icons type="close" size="14" color="#999"></uni-icons>
        </view>
      </view>
      <!-- <view class="filter-btn" @click="showFilterOptions">
        <uni-icons type="filter" size="20" color="#666"></uni-icons>
        <text class="filter-text">筛选</text>
      </view> -->
    </view>
    
    <!-- 分类标签 -->
    <view class="category-tabs">
      <scroll-view scroll-x="true" class="category-scroll" show-scrollbar="false">
        <view class="category-list">
          <view 
            v-for="(category, index) in categories" 
            :key="index"
            :class="['category-item', selectedCategory === category.id ? 'category-active' : '']"
            @click="selectCategory(category.id)"
          >
            {{ category.name }}
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 商品列表 -->
    <view class="product-list">
      <view 
        v-for="product in displayProducts" 
        :key="product.id" 
        class="product-card"
        :class="{'inactive-product': product.status !== 1}"
      >
        <view class="product-image-container">
          <image class="product-image" :src="getProductImage(product)" mode="aspectFill"></image>
          <view v-if="product.status !== 1" class="inactive-badge">已下架</view>
          <view v-else-if="product.totalStock <= product.safeStock" class="low-stock-badge">库存紧张</view>
        </view>
        <view class="product-info">
          <view class="product-name">{{ product.name }}</view>
          <view class="product-meta">
            <view class="product-price">¥{{ formatPrice(product.price) }}</view>
            <view class="product-stock">库存: {{ product.totalStock }}</view>
          </view>
          <view class="product-category-tag">{{ getCategoryName(product.categoryId) }}</view>
          <view class="product-sales">安全库存: {{ product.safeStock }}</view>
          <view class="product-merchant">商家: {{ getMerchantName(product.merchantId) }}</view>
        </view>
        <view class="product-actions">
          <view class="action-btn view-btn" @click="viewProductDetail(product.id)">
            <uni-icons type="eye" size="16" color="#FF8C42"></uni-icons>
            <text>查看</text>
          </view>
          <view 
            class="action-btn status-btn" 
            :class="product.status === 1 ? 'remove-btn' : 'restock-btn'"
            @click="toggleProductStatus(product.id)"
          >
            <uni-icons :type="product.status === 1 ? 'eye-slash' : 'eye'" size="16" :color="product.status === 1 ? '#666' : '#FF8C42'"></uni-icons>
            <text>{{ product.status === 1 ? '下架' : '上架' }}</text>
          </view>
          <view class="action-btn edit-btn" @click="editProduct(product)">
            <uni-icons type="edit" size="16" color="#666"></uni-icons>
            <text>编辑</text>
          </view>
          <view class="action-btn delete-btn" @click="deleteProduct(product.id)">
            <uni-icons type="trash" size="16" color="#fff"></uni-icons>
            <text>删除</text>
          </view>
        </view>
      </view>
      
      <!-- 加载中状态 -->
      <view v-if="isLoading" class="loading-state">
        <uni-icons type="spinner-cycle" size="30" color="#FF8C42"></uni-icons>
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 空状态 -->
      <view v-if="!isLoading && displayProducts.length === 0" class="empty-state">
        <image class="empty-image" src="/static/empty-box.png"></image>
        <text class="empty-text">{{ searchKeyword ? '未找到相关商品' : '暂无商品数据' }}</text>
      </view>
    </view>
    
    <!-- 分页控制 -->
    <view v-if="totalPages > 1" class="pagination">
      <view 
        class="pagination-btn prev-btn" 
        :class="{ 'disabled': currentPage === 1 }"
        @click="prevPage"
      >
        <uni-icons type="left" size="14" :color="currentPage === 1 ? '#ccc' : '#666'"></uni-icons>
        <text>上一页</text>
      </view>
      <view class="pagination-info">{{ currentPage }} / {{ totalPages }}</view>
      <view 
        class="pagination-btn next-btn" 
        :class="{ 'disabled': currentPage === totalPages }"
        @click="nextPage"
      >
        <text>下一页</text>
        <uni-icons type="right" size="14" :color="currentPage === totalPages ? '#ccc' : '#666'"></uni-icons>
      </view>
    </view>
    
    <!-- 商品编辑弹窗 -->
    <view v-if="showProductModal" class="modal-overlay" @click="closeProductModal">
      <view class="product-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">编辑商品</text>
          <view class="modal-close" @click="closeProductModal">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">商品名称</text>
            <input 
              class="form-input" 
              v-model="editingProduct.name" 
              placeholder="请输入商品名称"
            />
          </view>
          <view class="form-item">
            <text class="form-label">商品描述</text>
            <textarea 
              class="form-textarea" 
              v-model="editingProduct.description" 
              placeholder="请输入商品描述"
            />
          </view>
          <view class="form-item">
            <text class="form-label">价格</text>
            <input 
              class="form-input" 
              v-model="editingProduct.price" 
              placeholder="请输入价格"
              type="digit"
            />
          </view>
          <view class="form-item">
            <text class="form-label">分类</text>
            <picker 
              :range="categoryOptions" 
              range-key="name" 
              :value="getCategoryIndex(editingProduct.categoryId)"
              @change="onCategoryChange"
            >
              <view class="picker-input">
                {{ getCategoryName(editingProduct.categoryId) }}
                <uni-icons type="down" size="14" color="#999"></uni-icons>
              </view>
            </picker>
          </view>
          <view class="form-item">
            <text class="form-label">总库存</text>
            <input 
              class="form-input" 
              v-model="editingProduct.totalStock" 
              placeholder="请输入总库存"
              type="number"
            />
          </view>
          <view class="form-item">
            <text class="form-label">安全库存</text>
            <input 
              class="form-input" 
              v-model="editingProduct.safeStock" 
              placeholder="请输入安全库存"
              type="number"
            />
          </view>
          <view class="form-item">
            <text class="form-label">状态</text>
            <view class="status-selector">
              <view 
                class="status-option" 
                :class="{ 'active': editingProduct.status === 1 }"
                @click="editingProduct.status = 1"
              >
                上架
              </view>
              <view 
                class="status-option" 
                :class="{ 'active': editingProduct.status === 0 }"
                @click="editingProduct.status = 0"
              >
                下架
              </view>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <view class="cancel-btn" @click="closeProductModal">取消</view>
          <view class="confirm-btn" @click="saveProduct">保存</view>
        </view>
      </view>
    </view>
    
    <!-- 商品详情弹窗 -->
    <view v-if="showDetailModal" class="modal-overlay" @click="closeDetailModal">
      <view class="detail-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">商品详情</text>
          <view class="modal-close" @click="closeDetailModal">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>
        <view class="modal-body">
          <!-- 商品图片 -->
          <view class="detail-image-section">
            <image class="detail-image" :src="getProductImage(viewingProduct)" mode="aspectFill"></image>
            <view class="detail-status">
              <view class="status-badge" :class="viewingProduct.status === 1 ? 'status-active' : 'status-inactive'">
                {{ viewingProduct.status === 1 ? '在售' : '已下架' }}
              </view>
              <view v-if="viewingProduct.status === 1 && viewingProduct.totalStock <= viewingProduct.safeStock" class="stock-warning">
                库存预警
              </view>
            </view>
          </view>
          
          <!-- 基本信息 -->
          <view class="detail-section">
            <view class="section-title">基本信息</view>
            <view class="detail-row">
              <text class="detail-label">商品名称</text>
              <text class="detail-value">{{ viewingProduct.name }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">商品描述</text>
              <text class="detail-value">{{ viewingProduct.description || '暂无描述' }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">商品分类</text>
              <text class="detail-value">{{ getCategoryName(viewingProduct.categoryId) }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">所属商家</text>
              <text class="detail-value">{{ getMerchantName(viewingProduct.merchantId) }}</text>
            </view>
          </view>
          
          <!-- 价格信息 -->
          <view class="detail-section">
            <view class="section-title">价格信息</view>
            <view class="detail-row">
              <text class="detail-label">销售价格</text>
              <text class="detail-value price-highlight">¥{{ formatPrice(viewingProduct.price) }}</text>
            </view>
          </view>
          
          <!-- 库存信息 -->
          <view class="detail-section">
            <view class="section-title">库存信息</view>
            <view class="detail-row">
              <text class="detail-label">当前库存</text>
              <text class="detail-value" :class="viewingProduct.totalStock <= viewingProduct.safeStock ? 'stock-low' : ''">
                {{ viewingProduct.totalStock }}
              </text>
            </view>
            <view class="detail-row">
              <text class="detail-label">安全库存</text>
              <text class="detail-value">{{ viewingProduct.safeStock }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">库存状态</text>
              <text class="detail-value" :class="viewingProduct.totalStock <= viewingProduct.safeStock ? 'stock-low' : 'stock-normal'">
                {{ viewingProduct.totalStock <= viewingProduct.safeStock ? '库存不足' : '库存充足' }}
              </text>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <view class="close-btn" @click="closeDetailModal">关闭</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
/* @ts-nocheck */
import { ref, reactive, computed, onMounted } from 'vue'

// 基础数据
const statusBarHeight = ref(0)
const searchKeyword = ref('')
const selectedCategory = ref('all')
const allProducts = ref([])
const isLoading = ref(false)
const showProductModal = ref(false)
const isEditMode = ref(false)

// 商品详情弹窗相关
const showDetailModal = ref(false)
const viewingProduct = reactive({
  id: null,
  name: '',
  description: '',
  price: 0,
  categoryId: null,
  totalStock: 0,
  safeStock: 0,
  status: 1,
  mainImageUrl: '',
  merchantId: null
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(1)
const totalRecords = ref(0)

// 商家数据
const merchants = ref([])

// 编辑商品数据
const editingProduct = reactive({
  id: null,
  name: '',
  description: '',
  price: 0,
  categoryId: null,
  totalStock: 0,
  safeStock: 0,
  status: 1,
  mainImageUrl: '',
  merchantId: null
})

// 商品统计数据
const productStats = reactive({
  totalProducts: 0,
  activeProducts: 0,
  lowStockCount: 0,
  inactiveProducts: 0
})

// 商品分类
const categories = [
  { id: 'all', name: '全部' },
  { id: 1, name: '食品饮料' },
  { id: 2, name: '零食小吃' },
  { id: 3, name: '饮料冲调' },
  { id: 4, name: '休闲食品' },
  { id: 5, name: '日用百货' },
  { id: 6, name: '洗护用品' },
  { id: 7, name: '清洁用品' },
  { id: 8, name: '个人护理' },
  { id: 9, name: '数码电子' },
  { id: 10, name: '手机配件' },
  { id: 11, name: '电脑周边' }
]

// 分类选项（不包含"全部"）
const categoryOptions = computed(() => {
  return categories.filter(c => c.id !== 'all')
})

// 获取当前日期
const currentDate = computed(() => {
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth() + 1
  const day = now.getDate()
  return `${year}年${month}月${day}日`
})

// 当前页显示的商品
const displayProducts = computed(() => {
  let filteredProducts = allProducts.value

  // 应用搜索过滤
  if (searchKeyword.value) {
    filteredProducts = filteredProducts.filter(product => 
      product.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }

  // 应用分类过滤
  if (selectedCategory.value !== 'all') {
    filteredProducts = filteredProducts.filter(p => 
      p.categoryId === selectedCategory.value
    )
  }

  // 更新总记录数和总页数
  totalRecords.value = filteredProducts.length
  totalPages.value = Math.ceil(totalRecords.value / pageSize.value)

  // 应用分页
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  
  return filteredProducts.slice(startIndex, endIndex)
})

// 获取状态栏高度
const getStatusBarHeight = () => {
  try {
    const systemInfo = uni.getSystemInfoSync()
    statusBarHeight.value = systemInfo.statusBarHeight || 0
  } catch (e) {
    console.error('获取系统信息失败:', e)
    statusBarHeight.value = 0
  }
}

// 模拟商家数据
const mockMerchants = [
  { id: 1, shopName: "优品超市", username: "merchant1" },
  { id: 2, shopName: "好物便利店", username: "merchant2" },
  { id: 3, shopName: "生活小站", username: "merchant3" },
  { id: 4, shopName: "电子世界", username: "merchant4" }
]

// 基于图片的模拟商品数据
const mockProductsData = [
  {
    id: 1,
    name: "可口可乐",
    description: "碳酸饮料，500ml",
    price: 3.50,
    categoryId: 3,
    totalStock: 120,
    safeStock: 20,
    status: 1,
    mainImageUrl: "/static/cola.png",
    merchantId: 1
  },
  {
    id: 2,
    name: "乐事薯片",
    description: "美国经典原味，75g",
    price: 8.50,
    categoryId: 2,
    totalStock: 85,
    safeStock: 15,
    status: 1,
    mainImageUrl: "/static/lays.png",
    merchantId: 1
  },
  {
    id: 3,
    name: "农夫山泉",
    description: "天然水，550ml",
    price: 2.00,
    categoryId: 3,
    totalStock: 200,
    safeStock: 30,
    status: 1,
    mainImageUrl: "/static/nongfuwater.png",
    merchantId: 2
  },
  {
    id: 4,
    name: "卡乐比麦片",
    description: "水果麦片，400g",
    price: 38.00,
    categoryId: 4,
    totalStock: 45,
    safeStock: 10,
    status: 1,
    mainImageUrl: "/static/calbee.png",
    merchantId: 2
  },
  {
    id: 5,
    name: "康师傅红烧牛肉面",
    description: "方便面，袋装，90g",
    price: 4.50,
    categoryId: 4,
    totalStock: 150,
    safeStock: 25,
    status: 1,
    mainImageUrl: "/static/kangshifu.png",
    merchantId: 3
  },
  {
    id: 6,
    name: "舒肤佳香皂",
    description: "清香型，100g*3块装",
    price: 15.90,
    categoryId: 6,
    totalStock: 75,
    safeStock: 12,
    status: 1,
    mainImageUrl: "/static/safeguard.png",
    merchantId: 3
  },
  {
    id: 7,
    name: "蓝月亮洗衣液",
    description: "薰衣草香，2kg",
    price: 29.90,
    categoryId: 7,
    totalStock: 60,
    safeStock: 8,
    status: 1,
    mainImageUrl: "/static/bluemoon.png",
    merchantId: 3
  },
  {
    id: 8,
    name: "高露洁牙膏",
    description: "茶健康，120g",
    price: 12.50,
    categoryId: 8,
    totalStock: 90,
    safeStock: 15,
    status: 1,
    mainImageUrl: "/static/360.png",
    merchantId: 2
  },
  {
    id: 9,
    name: "清风抽纸",
    description: "原木纸巾，3层*120抽*10包",
    price: 27.90,
    categoryId: 7,
    totalStock: 40,
    safeStock: 8,
    status: 1,
    mainImageUrl: "/static/paper.png",
    merchantId: 1
  },
  {
    id: 10,
    name: "苹果数据线",
    description: "Lightning接口，1m",
    price: 39.00,
    categoryId: 10,
    totalStock: 25,
    safeStock: 5,
    status: 1,
    mainImageUrl: "/static/charge.png",
    merchantId: 4
  },
  {
    id: 11,
    name: "罗技鼠标",
    description: "无线鼠标，M185",
    price: 69.00,
    categoryId: 11,
    totalStock: 30,
    safeStock: 6,
    status: 1,
    mainImageUrl: "/static/mouse.png",
    merchantId: 4
  },
  {
    id: 12,
    name: "小米充电宝",
    description: "10000mAh",
    price: 79.00,
    categoryId: 10,
    totalStock: 18,
    safeStock: 5,
    status: 1,
    mainImageUrl: "/static/chargebao.png",
    merchantId: 4
  }
]

// 获取商家列表 - 使用模拟数据
const fetchMerchants = async () => {
  merchants.value = mockMerchants
}

// 获取商品数据 - 使用模拟数据
const fetchProducts = async () => {
  isLoading.value = true
  try {
    // 使用基于图片的模拟数据
    allProducts.value = mockProductsData
    
    // 更新统计数据
    updateProductStats()
    
  } catch (error) {
    console.error('获取商品数据出错:', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 更新商品统计数据
const updateProductStats = () => {
  const products = allProducts.value
  
  productStats.totalProducts = products.length
  productStats.activeProducts = products.filter(p => p.status === 1).length
  productStats.inactiveProducts = products.filter(p => p.status === 0).length
  productStats.lowStockCount = products.filter(p => 
    p.status === 1 && p.totalStock <= p.safeStock
  ).length
}

// 格式化价格
const formatPrice = (price: any) => {
  if (typeof price === 'number') {
    return price.toFixed(2)
  }
  return '0.00'
}

// 获取商品图片
const getProductImage = (product: any) => {
  if (product.mainImageUrl) {
    return product.mainImageUrl
  }
  return `/placeholder.svg?height=120&width=120&text=${encodeURIComponent(product.name || '商品')}`
}

// 获取分类名称
const getCategoryName = (categoryId: any) => {
  if (!categoryId) return '未分类'
  const category = categories.find(c => c.id === categoryId)
  return category ? category.name : '未分类'
}

// 获取分类索引
const getCategoryIndex = (categoryId: any) => {
  if (!categoryId) return 0
  const index = categoryOptions.value.findIndex(c => c.id === categoryId)
  return index >= 0 ? index : 0
}

// 分类选择事件
const onCategoryChange = (e: any) => {
  const index = e.detail.value
  if (index >= 0 && index < categoryOptions.value.length) {
    const selectedCategory = categoryOptions.value[index]
    editingProduct.categoryId = (selectedCategory as any).id
  }
}

// 获取商家名称
const getMerchantName = (merchantId: any) => {
  if (!merchantId) return '未知商家'
  
  // 如果没有商家数据，直接返回商家ID
  if (!merchants.value || merchants.value.length === 0) {
    return `商家${merchantId}`
  }
  
  const merchantList = merchants.value
  const merchant = (merchantList as any[]).find((m: any) => m.id === merchantId)
  return merchant ? (merchant.shopName || merchant.username || `商家${merchantId}`) : `商家${merchantId}`
}

// 重置编辑表单
const resetEditingProduct = () => {
  Object.assign(editingProduct, {
    id: null,
    name: '',
    description: '',
    price: 0,
    categoryId: null,
    totalStock: 0,
    safeStock: 0,
    status: 1,
    mainImageUrl: '',
    merchantId: null
  })
}

// 刷新数据
const refreshData = async () => {
  uni.showLoading({ title: '刷新中...' })
  try {
    await fetchProducts()
    uni.showToast({
      title: '数据已刷新',
      icon: 'success'
    })
  } catch (error) {
    uni.showToast({
      title: '刷新失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 选择分类
const selectCategory = (categoryId: any) => {
  selectedCategory.value = categoryId
  currentPage.value = 1
}

// 搜索输入事件
const onSearchInput = () => {
  if (searchKeyword.value === '') {
    currentPage.value = 1
  }
}

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = ''
  currentPage.value = 1
}

// 搜索商品
const searchProducts = () => {
  currentPage.value = 1
}

// 显示筛选选项
// const showFilterOptions = () => {
//   uni.showActionSheet({
//     itemList: ['价格从高到低', '价格从低到高', '库存从高到低', '库存从低到高'],
//     success: (res) => {
//       uni.showToast({
//         title: '筛选功能开发中',
//         icon: 'none'
//       })
//     }
//   })
// }

// 关闭商品弹窗
const closeProductModal = () => {
  showProductModal.value = false
  resetEditingProduct()
}

// 保存商品 - 使用模拟操作
const saveProduct = async () => {
  if (!editingProduct.name) {
    uni.showToast({
      title: '请输入商品名称',
      icon: 'none'
    })
    return
  }
  
  if (!editingProduct.price || editingProduct.price <= 0) {
    uni.showToast({
      title: '请输入有效价格',
      icon: 'none'
    })
    return
  }
  
  uni.showLoading({ title: '更新中...' })
  
  try {
    // 更新现有商品
    const index = allProducts.value.findIndex(p => p.id === editingProduct.id)
    if (index !== -1) {
      allProducts.value[index] = {...editingProduct}
    }
    
    // 更新统计数据
    updateProductStats()
    
    uni.showToast({
      title: '商品更新成功',
      icon: 'success'
    })
    
    closeProductModal()
    
  } catch (error) {
    console.error('保存商品失败:', error)
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 查看商品详情
const viewProductDetail = (productId: any) => {
  const product = allProducts.value.find(p => p.id === productId)
  if (product) {
    Object.assign(viewingProduct, {
      id: product.id,
      name: product.name || '',
      description: product.description || '',
      price: product.price || 0,
      categoryId: product.categoryId || null,
      totalStock: product.totalStock || 0,
      safeStock: product.safeStock || 0,
      status: product.status || 1,
      mainImageUrl: product.mainImageUrl || '',
      merchantId: product.merchantId || null
    })
    showDetailModal.value = true
  }
}

// 关闭商品详情弹窗
const closeDetailModal = () => {
  showDetailModal.value = false
}

// 切换商品状态
const toggleProductStatus = async (productId: any) => {
  const products = allProducts.value
  const productIndex = (products as any[]).findIndex((product: any) => product.id === productId)
  if (productIndex === -1) return
  
  const product = (products as any[])[productIndex]
  const newStatus = product.status === 1 ? 0 : 1
  
  uni.showModal({
    title: '确认操作',
    content: `确定要${newStatus === 1 ? '上架' : '下架'}商品"${product.name}"吗？`,
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '处理中...' })
        
        try {
          // 更新本地数据
          if ((allProducts.value as any[])[productIndex]) {
            ;(allProducts.value as any[])[productIndex].status = newStatus
          }
          updateProductStats()
          
          uni.showToast({
            title: `商品已${newStatus === 1 ? '上架' : '下架'}`,
            icon: 'success'
          })
        } catch (error) {
          console.error('更新商品状态失败:', error)
          uni.showToast({
            title: '操作失败',
            icon: 'none'
          })
        } finally {
          uni.hideLoading()
        }
      }
    }
  })
}

// 编辑商品
const editProduct = (product: any) => {
  isEditMode.value = true
  Object.assign(editingProduct, {
    id: product.id,
    name: product.name || '',
    description: product.description || '',
    price: product.price || 0,
    categoryId: product.categoryId || null,
    totalStock: product.totalStock || 0,
    safeStock: product.safeStock || 0,
    status: product.status || 1,
    mainImageUrl: product.mainImageUrl || '',
    merchantId: product.merchantId || null
  })
  showProductModal.value = true
}

// 删除商品
const deleteProduct = (productId: any) => {
  const products = allProducts.value
  const product = (products as any[]).find((product: any) => product.id === productId)
  if (!product) return
  
  uni.showModal({
    title: '确认删除',
    content: `确定要删除商品"${product.name}"吗？此操作不可恢复！`,
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '删除中...' })
        
        try {
          // 从本地数据中删除
          const index = allProducts.value.findIndex(p => p.id === productId)
          if (index !== -1) {
            allProducts.value.splice(index, 1)
          }
          
          // 更新统计数据
          updateProductStats()
          
          uni.showToast({
            title: '商品已删除',
            icon: 'success'
          })
        } catch (error) {
          console.error('删除商品失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        } finally {
          uni.hideLoading()
        }
      }
    }
  })
}

// 分页控制 - 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

// 分页控制 - 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

// 页面加载时执行
onMounted(async () => {
  console.log('商品管理页面加载完成')
  getStatusBarHeight()
  
  try {
    await fetchMerchants()
    await fetchProducts()
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
})
</script>

<style>
.product-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background: linear-gradient(135deg, #FF8C42 0%, #FF6B35 100%);
  color: white;
}

.title-section {
  display: flex;
  flex-direction: column;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.date {
  font-size: 24rpx;
  opacity: 0.9;
}

.refresh-btn {
  padding: 16rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
}

.stats-overview {
  padding: 30rpx;
  background-color: white;
  margin-bottom: 20rpx;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  border: 1rpx solid #f0f0f0;
}

.stat-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  background: linear-gradient(135deg, #FF8C42 0%, #FF6B35 100%);
}

.stat-content {
  flex: 1;
}

.stat-label {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.stat-value {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.action-bar {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: white;
  margin-bottom: 20rpx;
  gap: 20rpx;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 25rpx;
  padding: 0 20rpx;
  height: 70rpx;
}

.search-box input {
  flex: 1;
  margin-left: 15rpx;
  font-size: 28rpx;
  background: transparent;
}

.clear-search {
  padding: 10rpx;
}

.filter-btn {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #f5f5f5;
  border-radius: 25rpx;
  gap: 10rpx;
}

.filter-text {
  font-size: 28rpx;
  color: #666;
}

.category-tabs {
  background-color: white;
  margin-bottom: 20rpx;
}

.category-scroll {
  white-space: nowrap;
}

.category-list {
  display: flex;
  padding: 20rpx 30rpx;
  gap: 20rpx;
}

.category-item {
  padding: 16rpx 32rpx;
  background-color: #f5f5f5;
  border-radius: 25rpx;
  font-size: 28rpx;
  color: #666;
  white-space: nowrap;
  transition: all 0.3s ease;
}

.category-active {
  background: linear-gradient(135deg, #FF8C42 0%, #FF6B35 100%);
  color: white;
}

.product-list {
  padding: 0 30rpx;
}

.product-card {
  display: flex;
  background-color: white;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  position: relative;
  transition: all 0.3s ease;
}

.inactive-product {
  opacity: 0.7;
}

.product-image-container {
  position: relative;
  margin-right: 20rpx;
}

.product-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  background-color: #f5f5f5;
}

.inactive-badge,
.low-stock-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background-color: #ff4757;
  color: white;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
}

.low-stock-badge {
  background-color: #ffa502;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.product-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  font-size: 28rpx;
  color: #FF8C42;
  font-weight: bold;
}

.product-stock {
  font-size: 24rpx;
  color: #666;
}

.product-category-tag {
  display: inline-block;
  background-color: #e8f4fd;
  color: #1890ff;
  font-size: 22rpx;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
  align-self: flex-start;
}

.product-sales,
.product-merchant {
  font-size: 24rpx;
  color: #999;
}

.product-actions {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  margin-left: 20rpx;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12rpx 20rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  gap: 8rpx;
  min-width: 120rpx;
  transition: all 0.3s ease;
}

.view-btn {
  background-color: #fff2e8;
  color: #FF8C42;
  border: 1rpx solid #FF8C42;
}

.remove-btn {
  background-color: #f5f5f5;
  color: #666;
  border: 1rpx solid #ddd;
}

.restock-btn {
  background-color: #fff2e8;
  color: #FF8C42;
  border: 1rpx solid #FF8C42;
}

.edit-btn {
  background-color: #f5f5f5;
  color: #666;
  border: 1rpx solid #ddd;
}

.delete-btn {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1rpx solid #ff4d4f;
}

.loading-state,
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  color: #999;
}

.loading-text {
  margin-top: 20rpx;
  font-size: 28rpx;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: white;
  margin: 20rpx 30rpx;
  border-radius: 16rpx;
}

.pagination-btn {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  gap: 8rpx;
  background-color: #f5f5f5;
  color: #666;
}

.pagination-btn.disabled {
  opacity: 0.5;
}

.pagination-info {
  font-size: 28rpx;
  color: #333;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.product-modal {
  background-color: white;
  border-radius: 16rpx;
  width: 90%;
  max-height: 80vh;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.modal-close {
  padding: 10rpx;
}

.modal-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background-color: #f9f9f9;
}

.form-textarea {
  height: 120rpx;
  resize: none;
}

.picker-input {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  background-color: #f9f9f9;
  font-size: 28rpx;
}

.status-selector {
  display: flex;
  gap: 20rpx;
}

.status-option {
  flex: 1;
  padding: 20rpx;
  text-align: center;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #666;
  background-color: #f9f9f9;
}

.status-option.active {
  background: linear-gradient(135deg, #FF8C42 0%, #FF6B35 100%);
  color: white;
  border-color: #FF8C42;
}

.modal-footer {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.cancel-btn,
.confirm-btn {
  flex: 1;
  padding: 24rpx;
  text-align: center;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background: linear-gradient(135deg, #FF8C42 0%, #FF6B35 100%);
  color: white;
}

.detail-modal {
  background-color: white;
  border-radius: 16rpx;
  width: 90%;
  max-height: 85vh;
  overflow: hidden;
}

.detail-image-section {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

.detail-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 16rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
}

.detail-status {
  position: absolute;
  top: 30rpx;
  right: 30rpx;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.status-badge {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  text-align: center;
  font-weight: bold;
}

.status-active {
  background-color: #52c41a;
  color: white;
}

.status-inactive {
  background-color: #ff4d4f;
  color: white;
}

.stock-warning {
  padding: 6rpx 12rpx;
  background-color: #faad14;
  color: white;
  border-radius: 16rpx;
  font-size: 22rpx;
  text-align: center;
}

.detail-section {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.detail-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  padding-bottom: 10rpx;
  border-bottom: 2rpx solid #FF8C42;
  display: inline-block;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.detail-row:last-child {
  border-bottom: none;
}

.detail-label {
  font-size: 28rpx;
  color: #666;
  flex: 0 0 160rpx;
}

.detail-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  text-align: right;
  word-break: break-all;
}

.price-highlight {
  color: #FF8C42;
  font-weight: bold;
  font-size: 32rpx;
}

.stock-low {
  color: #ff4d4f;
  font-weight: bold;
}

.stock-normal {
  color: #52c41a;
  font-weight: bold;
}

.close-btn {
  flex: 1;
  padding: 24rpx;
  text-align: center;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: linear-gradient(135deg, #FF8C42 0%, #FF6B35 100%);
  color: white;
}
</style>
